package com.hjtech.baselib.utils

import android.content.Context
import android.net.ConnectivityManager
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

/*
 * 项目名:    Pigeon
 * 包名       cn.hjtech.directory.common.utils
 * 文件名:    NetWorkUtil
 * 创建者:    ZJB
 * 创建时间:  2017/5/20 on 13:22
 * 描述:     TODO
 */
object NetWorkUtil {

    /**
     * 请求网络是否成功来判断手机是否可以上网
     *
     * @return boolean
     */
    private val isAvailable: Boolean
        get() {
            try {
                val url = URL("http://www.baidu.com")
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.readTimeout = 1000
                connection.connectTimeout = 1000
                connection.connect()
                return connection.responseCode == 200
            } catch (e: IOException) {
                e.printStackTrace()
                return false
            }

        }

    /**
     * 检测wifi是否连接
     *
     * @return
     */
    fun isWifiConnected(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = cm.activeNetworkInfo
        return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI
    }

    /**
     * 检测3G是否连接
     *
     * @return
     */
    fun is3gConnected(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = cm.activeNetworkInfo
        return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_MOBILE
    }

    /**
     * 请求网络是否成功来判断手机是否可以上网
     */
    fun isNetWorkAvailable(available: NetWorkAvailable?) {
        Observable.create(ObservableOnSubscribe<Boolean> { e -> e.onNext(isAvailable) }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Boolean> {
            override fun onNext(t: Boolean) {
                available?.available(t!!)
            }

            override fun onSubscribe(d: Disposable) {

            }


            override fun onError(e: Throwable) {
                available?.available(false)
            }

            override fun onComplete() {

            }
        })

    }

    interface NetWorkAvailable {
        fun available(b: Boolean)
    }
}
